import { EditorView, WidgetType } from "@codemirror/view";
import { Decoration, ViewPlugin, MatchDecorator } from "@codemirror/view";

class FunctionWidget extends WidgetType {
  text;

  constructor(text) {
    super();
    this.text = text;
  }

  eq(other) {
    return this.text == other.text;
  }

  toDOM() {
    const elt = document.createElement("span");
    elt.style.cssText = `
      color: #093aff;
      font-size: 14px;
      `;
    elt.textContent = this.text;
    return elt;
  }

  ignoreEvent() {
    return true;
  }
}

const functionMatcher = new MatchDecorator({
  regexp: /func\.[\u4e00-\u9fa5a-zA-Z]+/g,
  decoration: (match) => {
    return Decoration.replace({
      widget: new FunctionWidget(`${match[0].replace("func.", "")}`),
    });
  },
});

export const functionPlugin = ViewPlugin.fromClass(
  class {
    function;

    constructor(view) {
      this.function = functionMatcher.createDeco(view);
    }

    update(update) {
      this.function = functionMatcher.updateDeco(update, this.function);
    }
  },
  {
    decorations: (instance) => {
      return instance.function;
    },
    provide: (plugin) =>
      EditorView.atomicRanges.of((view) => {
        return view.plugin(plugin)?.function || Decoration.none;
      }),
  }
);
